package com.net.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName NettyServerInitializer
 * @Description TODO
 * @Author zhuchen216628
 * @Date 2018/9/28 10:49
 * @Version 1.0
 **/
@Component
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

    //提前注入一次，避免在多例中得不到注入
    @Autowired
    private ConnectManager connectManager;

    @Autowired
    private BeanFactory beanFactory;

    IdleHandler idleHandler;

    public NettyServerInitializer(){
        System.out.println("NettyServerInitializer");
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

//        pipeline.addLast(new IdleStateHandler(10, 5, 3, TimeUnit.SECONDS));
//        pipeline.addLast(idleHandler);

        // 以("\n")为结尾分割的 解码器
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));

        // 字符串解码 和 编码
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());

        // 超时心跳相关
        pipeline.addLast(new IdleStateHandler(10, 5, 3, TimeUnit.SECONDS));
        pipeline.addLast(new IdleHandler());
        // 自己的逻辑Handler
        NettyServerHandler nettyServerHandler = (NettyServerHandler) beanFactory.getBean("nettyServerHandler");
        pipeline.addLast("handler", nettyServerHandler);

    }
}
